package com.example.booksystem.service;



import com.example.booksystem.model.Book;
import com.example.booksystem.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookServiceLmpl implements BookService {
    @Autowired
    private BookRepository bookRepository;

    @Override
    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    @Override
    public void saveBook(Book book) {
        this.bookRepository.save(book);

    }


    //通过bookname来查询数据
    @Override
    public List<Book> findByNameContaining(String bookname) {
        List<Book> bookList = bookRepository.findByBookName(bookname);

        return bookList;
    }

    @Override
    public Book getBookByid(Long id) {
        Optional<Book> optional = bookRepository.findById(id);
        Book book = null;
        if( optional.isPresent()){
            book = optional.get();
        }else{
            throw new RuntimeException(" 查无此书，请重输入, id :  "+ id);
        }
        return book;
    }

    @Override
    public void deleteBookByid(Long id) {
        bookRepository.deleteById(id);
    }


    @Override
    public Page<Book> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        //设置排序参数，升序ASC/降序DESC？
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();

        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        return this.bookRepository.findAll(pageable);
    }




}
